import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from '@/stores/user.js'  

import { insertCartAPI,findNewCartListAPI,delCartAPI } from '@/apis/cart.js'

//分类数据缓存 与他有关的怎么获取也封装，只暴露分类数据
export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)

    //存的是  鞋子:1  balabala
    const cartList=ref([])
    const addCart = async(goods) => {
        
        if (isLogin.value) {
            const { skuId, count } = goods
            //如果登录的话
            await insertCartAPI({ skuId, count })
            updateNewList()
        } else {
             //有则count+1 无则push
        const item = cartList.value.find((item) => item.skuId === goods.skuId) 
        if (item) {
            item.count++
        }
        else {
            cartList.value.push(goods)
        }
        }
       
    }
    const delCart = async(skuId) => {
        if (isLogin.value) {
            //调用接口   相当于一次更新 更新完存在本地 不同地方拿数据的时候就不需要重新获取了 这里是增量维护
            await delCartAPI([skuId])
            updateNewList()
            
        } else {
            cartList.value=cartList.value.filter((item)=>item.skuId!==skuId)

        }

    }
    const clearCart = () => {
        cartList.value=[]
    }

    //计算属性 总数量和总价
    const allCount = computed(() => {
        return cartList.value.reduce((pre, item) => pre + item.count, 0)
    })
    const allPrice = computed(() => {
        return cartList.value.reduce((pre, item) => pre + item.count * item.price, 0)
    })
    const isAll = computed(() => {
        return cartList.value.every((item) => item.selected)
    })
    //单选改变
    const singleCheck = (skuId,selected) => {
        //修改skuId对应的
        cartList.value.forEach((item) => {
            if (item.skuId === skuId) {
                item.selected=selected
            }
        })
    }

    //全选和全不选
    const allCheck = (selected) => {
        cartList.value.forEach((item) => {
            item.selected=selected
        })
    }
    
    //已选择数量
    const selectedCount = computed(() => {
        return cartList.value.filter((item) => item.selected).reduce((pre, item) => pre + item.count, 0)
    })

    //已选商品总价
    const selectedPrice = computed(() => {
        return cartList.value.filter((item) => item.selected).reduce((pre, item) => pre + item.count * item.price, 0)
    })

    const updateNewList = async () => {
        const res = await findNewCartListAPI()
        cartList.value=res.result
    }

  return { clearCart,cartList, addCart ,delCart,allCount,allPrice,singleCheck,isAll,allCheck,selectedCount,selectedPrice,updateNewList}
}, {
    persist: true
})
